﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

public class ToolHelper
{
    /// <summary>
    /// 保存Excel
    /// </summary>
    /// <param name="list">数据源</param>
    /// <param name="strDefineHead">列别名</param>
    /// <param name="Fields">字段</param>
    /// <param name="FileName">文件名</param>
    public static void CreateExcel<T>(string title, IList<T> list, string strDefineHead, string Fields, string FileName)
    {
        StringBuilder ls_item = new StringBuilder();
        string[] tmpHead = strDefineHead.Split(',');
        string[] tmpFields = Fields.Split(',');

        //载入标题
        foreach (string item in tmpHead)
        {
            ls_item.Append(item + "\t");
        }
        ls_item.Append("\r\n");

        foreach (T t in list)
        {
            PropertyInfo[] propertys = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (string item in tmpFields)
            {
                PropertyInfo pi = propertys.Where(x => x.Name == item).FirstOrDefault();
                //if (pi == null || !pi.CanWrite) continue;
                if (pi == null) continue;
                if (!tmpFields.Contains(pi.Name)) continue;

                var value = pi.GetValue(t, null);
                //if (pi.PropertyType.IsEnum)
                //    value = ((Enum)Enum.Parse(pi.PropertyType, value.ToString(), true)).ToDescription();

                if (value != null && Regex.Match(value.ToString(), "^\\d+$").Success && value.ToString().Length > 8)
                    ls_item.Append("'");

                ls_item.Append(value == null ? "" : value.ToString().Replace("\t", "").Replace("\r", "").Replace("\n", ""));
                ls_item.Append("\t");
            }
            ls_item.Append("\r\n");
        }

        File.WriteAllText(FileName, ls_item.ToString(), Encoding.Unicode);
    }
}